package com.task.controller;

import com.task.controller.annotation.impl.UseControlImpl;
import com.task.controller.control.Control;
import com.task.controller.util.ReflectionsUtil;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.Closeable;

/**
 * 任务调度框架启动类
 */
public class TaskController implements Closeable {

    private HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.INFO, 0, TaskController.class.getCanonicalName());

    private static TaskController taskController = new TaskController();

    private Context context;

    private Control control;

    private TaskController() {
        super();
    }

    public static TaskController getInstance() {
        if (taskController == null) {
            taskController = new TaskController();
        }
        return taskController;
    }

    /**
     * 调用此方法初始化任务调度框架
     *
     * @param context 上下文对象
     * @return 任务调度框架主类对象
     */
    public TaskController init(Context context) {
        this.context = context;
        ReflectionsUtil.init(context);
        control = UseControlImpl.initControl(context);
        if (control == null) {
            throw new IllegalStateException("找不到默认的任务调度器，请使用debug尝试排查异常");
        }
        return this;
    }

    public Context getContext() {
        return context;
    }

    public Control getControl() {
        return control;
    }

    @Override
    public void close() {
        HiLog.info(LABEL_LOG, "释放任务调度器");
        context.getUITaskDispatcher().asyncDispatch(() -> {
            new ToastDialog(context).setText("释放任务调度器").show();
        });
        control.release();
    }
}
